package com.lfg.leetcode.leetcode0;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class No18FourSum {

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        if (nums.length < 4) {
            return ret;
        }
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 3; i++) {
            if ((long)nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) { //nums[i] is too large
                break;
            }
            if ((long)nums[i] + nums[nums.length - 1] + nums[nums.length - 2] + nums[nums.length - 3] < target) {//nums[i] is too small
                continue;
            }
            while (i > 0 && i < nums.length && nums[i] == nums[i - 1]) {
                i++;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if ((long)nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {   //nums[j] is too large
                    break;
                }
                if ((long)nums[i] + nums[j] + nums[nums.length - 1] + nums[nums.length - 2] < target) { // nums[j] is too small
                    continue;
                }
                if (j - 1 > i && j < nums.length && nums[j] == nums[j - 1]) {
                    continue;
                }
                int m = nums.length - 1;
                int n = j + 1;
                while (n < m) {
                    int sum = nums[n] + nums[m] + nums[i] + nums[j];
                    if (sum == target) {
                        List<Integer> l = new ArrayList<Integer>();
                        l.add(nums[i]);
                        l.add(nums[j]);
                        l.add(nums[n]);
                        l.add(nums[m]);


                        ret.add(l);
                        n++;
                        m--;
                        while (n < nums.length && nums[n] == nums[n - 1]) {
                            n++;
                        }
                        while (m > 0 && nums[m] == nums[m + 1]) {
                            m--;
                        }
                    } else if (sum > target) {
                        m--;
                    } else {
                        n++;
                    }
                }
            }
        }
        return ret;
    }


    public static void main(String[] args) {
        System.out.println(fourSum(new int[]{0,0,0,1000000000,1000000000,1000000000,1000000000}, 1000000000));
//        System.out.println(threeSum(new int[]{-2,0,0,2,2}));
    }
}
